package com.fast.develop.configuration.tools.print;

import cn.hutool.core.util.StrUtil;
import com.fast.develop.configuration.properties.FastDevelopPropesties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项 目 名：gs-builder-engine-parent
 * 源文件名：com.geekstorm.tto.builder.engine.configuration.print.PrintConsole
 * 文件版本：1.0.0
 * 创建人： 莫寅
 * 创建日期：2021-06-24 17:59
 * 修改作者：莫寅
 * 修改日期：2021-06-24 17:59
 * 文件描述：
 * by：2021 © CompanyName  , Inc. All Rights Reserved.
 */
@Slf4j
public class PrintConsole implements CommandLineRunner {

    private List<PrintMessage> printMessages = new ArrayList<>();

    private ApplicationContext applicationContext;
    private FastDevelopPropesties fastDevelopPropesties;

    public PrintConsole(ApplicationContext applicationContext, FastDevelopPropesties fastDevelopPropesties) {
        this.applicationContext = applicationContext;
        this.fastDevelopPropesties = fastDevelopPropesties;
    }

    public void print(){
        Environment environment = applicationContext.getEnvironment();
        String port = StrUtil.nullToDefault(environment.getProperty("server.port"), "8080");
        String contextPath = environment.getProperty("server.servlet.context-path");
        contextPath = contextPath == null ? "" : contextPath;

        for (int i = 0; i < printMessages.size(); i++) {
            PrintMessage printMessage = printMessages.get(i);
            Map variable = new HashMap<>();
            variable.put("port", port);
            variable.put("contextPath", contextPath);
            String msg = StrUtil.format(printMessage.getMessage(), variable);

            log.info(msg);
        }

    }

    @Override
    public void run(String... args) {
        print();
    }


    public void addPrintMessage(PrintMessage message){
        printMessages.add(message);
    }

    public void removePrintMessage(PrintMessage message){
        printMessages.remove(message);
    }

    public void addPrintMessage(int index, PrintMessage message){
        printMessages.add(index, message);
    }

    public void removePrintMessage(int index){
        printMessages.remove(index);
    }
}
